<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"
    >
      <el-form-item
        label="菜品名称"
        prop="name"
      >
        <el-input
          v-model="queryParams.name"
          placeholder="请输入菜品名称"
          clearable
          size="small"
          @input="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="菜品单价" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入菜品单价"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="菜品时段" prop="bornDate">
        <el-select v-model="queryParams.bornDate" placeholder="请选择菜品时段" clearable size="small">
          <el-option label="今天" value="2021-06-01" />
          <el-option label="明天" value="2021-06-02" />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="就餐类型" prop="diningType">
        <el-select v-model="queryParams.diningType" placeholder="请选择就餐类型" clearable size="small">
          <el-option label="早餐" value="1" />
          <el-option label="午餐" value="2" />
          <el-option label="晚餐" value="3" />
          <el-option label="接待餐" value="4" />
          <el-option label="其它" value="5" />
        </el-select>
      </el-form-item> -->
      <el-form-item
        label="菜品类型"
        prop="foodType"
      >
<!--        <el-select-->
<!--          v-model="queryParams.foodType"-->
<!--          placeholder="请选择菜品类型"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @change="handleQuery"-->
<!--        >-->
<!--          <el-option-->
<!--            label="套餐"-->
<!--            value="1"-->
<!--          />-->
<!--          <el-option-->
<!--            label="汤类"-->
<!--            value="2"-->
<!--          />-->
<!--          <el-option-->
<!--            label="主食"-->
<!--            value="3"-->
<!--          />-->
<!--          <el-option-->
<!--            label="甜品"-->
<!--            value="4"-->
<!--          />-->
<!--          <el-option-->
<!--            label="水果"-->
<!--            value="5"-->
<!--          />-->
<!--          <el-option-->
<!--            label="其它"-->
<!--            value="6"-->
<!--          />-->
<!--        </el-select>-->
        <el-select v-model="queryParams.foodType" placeholder="请选择菜品类型">
          <el-option
            v-for="item in foodTypes"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>

      </el-form-item>

      <el-form-item
        label="所属公司"
        prop="companyId"
      >
        <el-select
          v-model="queryParams.companyId"
          placeholder="请选择所属公司"
          clearable
          size="small"
          @change="handleQuery"
        >
          <el-option
            v-for="item in companys"
            :key="item.id"
            :label="item.text"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置</el-button>
      </el-form-item>
    </el-form>

    <el-row
      :gutter="10"
      class="mb8"
    >
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:food:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:food:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:food:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:food:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:food:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="foodList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        fixed
        label="序号"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum-1)*queryParams.pageSize+(scope.$index + 1)}} </span>
        </template>
      </el-table-column>
      <el-table-column
        label="菜品名称"
        align="center"
        prop="name"
      />
      <el-table-column
        label="菜品单价 (元)"
        align="center"
        prop="priceFormat"
      />
      <!-- <el-table-column label="菜品时段" align="center" prop="bornDate" /> -->
      <!-- <el-table-column label="就餐类型" align="center" prop="diningType">
              <template slot-scope="scope">
                  <span v-if="scope.row.diningType == 1">早餐</span>
                  <span v-if="scope.row.diningType == 2">午餐</span>
                  <span v-if="scope.row.diningType == 3">晚餐</span>
                  <span v-if="scope.row.diningType == 4">接待餐</span>
                  <span v-if="scope.row.diningType == 5">其它</span>
              </template>
      </el-table-column> -->
      <!--   <el-table-column label="菜品类型" align="center" prop="foodType" /> -->
      <el-table-column
        label="菜品类型"
        align="center"
        prop="foodType"
      >
<!--        <template slot-scope="scope">-->
<!--          <span v-if="scope.row.foodType == 1">套餐</span>-->
<!--          <span v-if="scope.row.foodType == 2">汤</span>-->
<!--          <span v-if="scope.row.foodType == 3">主食</span>-->
<!--          <span v-if="scope.row.foodType == 4">甜品</span>-->
<!--          <span v-if="scope.row.foodType == 5">水果</span>-->
<!--          <span v-if="scope.row.foodType == 6">其它</span>-->
<!--        </template>-->
        <template slot-scope="scope">
          <span>{{ foodTypes.filter(f => f.id == scope.row.foodType)[0].name}}</span>
        </template>
      </el-table-column>

<!--      <el-table-column-->
<!--        label="图片"-->
<!--        align="center"-->
<!--        prop="photo"-->
<!--      >-->
<!--        <template slot-scope="scope">-->
<!--          <img-->
<!--            :src="scope.row.photo"-->
<!--            class="news-image"-->
<!--          />-->
<!--        </template>-->
<!--      </el-table-column>-->

      <el-table-column label="图片" align="center" prop="photo" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.photo" :width="50" :height="50"/>
        </template>
      </el-table-column>

      <el-table-column
        label="所属公司"
        align="center"
        prop="companyName"
      />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:food:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:food:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="960px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item
          label="所属公司"
          prop="companyId"
        >
          <el-select
            v-model="form.companyId"
            placeholder="请选择所属公司"
            clearable
            size="small"
            style="width: 100%;"
            :disabled="notModifyCompany"
          >
            <el-option
              v-for="item in companys"
              :key="item.id"
              :label="item.text"
              :value="Number(item.id)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="菜品名称"
          prop="name"
        >
          <el-input
            v-model="form.name"
            placeholder="请输入菜品名称"
            maxlength="20"
            minlength="2"
          />
        </el-form-item>
        <el-form-item
          label="菜品单价"
          prop="price"
        >
          <el-input-number
            :min="0"
            v-model="form.price"
            placeholder="请输入菜品单价"
            style="width: 100%;"
          />
        </el-form-item>
        <!-- <el-form-item label="菜品时段" prop="bornDate">
        <el-select v-model="form.bornDate" placeholder="请选择菜品时段" clearable size="small" style="width: 100%;">
          <el-option v-for="item in dates" :key="item.id" :label="item.text" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
        <el-form-item label="就餐类型" prop="diningType">
        <el-select v-model="form.diningType" placeholder="请选择就餐类型" clearable size="small" style="width: 100%;">
          <el-option v-for="item in diningTypes" :key="item.id" :label="item.id" :value="item.value"></el-option>
        </el-select>
      </el-form-item> -->
        <el-form-item
          label="菜品类型"
          prop="foodType"
        >
          <el-select
            v-model="form.foodType"
            placeholder="请选择菜品类型"
            clearable
            size="small"
            style="width: 100%;"
          >
            <el-option
              v-for="item in foodTypes"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="图片路径" prop="photo">
          <el-input v-model="form.photo" placeholder="请输入图片路径" />
        </el-form-item> -->
<!--        <el-form-item-->
<!--          label="图片路径"-->
<!--          prop="photo"-->
<!--        >-->
<!--          <div class="updateimg">-->
<!--            <el-upload-->
<!--              :action="MixinUploadAllApi"-->
<!--              :on-success="uploadSuccess"-->
<!--              :on-remove="photo"-->
<!--              :file-list="fileListqiye"-->
<!--              :multiple="false"-->
<!--              :limit="1"-->
<!--              :before-upload="beforeImgUpload"-->
<!--            >-->
<!--              <el-button-->
<!--                size="small"-->
<!--                type="primary"-->
<!--              >点击上传</el-button>-->
<!--              <div-->
<!--                slot="tip"-->
<!--                class="el-upload__tip"-->
<!--              >-->
<!--                建议上传jpg/png文件，尺寸（宽*高）750*327-->
<!--              </div>-->
<!--            </el-upload>-->
<!--            <img :src="photo" />-->
<!--          </div>-->
<!--        </el-form-item>-->

        <el-form-item label="图片" prop="photo">
          <image-upload v-model="form.photo"/>
        </el-form-item>

      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="submitForm"
        >确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :action="upload.url"
        :headers="upload.headers"
        :before-upload="beforeFileUpload"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <!--        <div class="el-upload__tip" slot="tip">-->
        <!--          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据-->
        <!--          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>-->
        <!--        </div>-->
        <div
          class="el-upload__tip"
          style="color:red"
          slot="tip"
        >提示：仅允许导入“xls”或“xlsx”格式文件, 最大不超过10M！</div>
      </el-upload>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="submitFileForm"
        >确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listFood,
  getFood,
  delFood,
  addFood,
  updateFood,
  exportFood,
} from "@/api/food/food";
import { getDate } from "@/api/diningType/type";
import { getToken } from "@/utils/auth";
import { getCompanys } from "@/api/system/dept";
import { listType } from "@/api/foodType/type";

export default {
  name: "Food",
  data() {
    return {
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        headers: { Authorization: "Bearer " + getToken() },
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/food/import",
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      foodList: [],
      fileListqiye: [],
      // 时间信息
      dates: [],
      // 公司信息
      companys: [],
      // 公司能否修改
      notModifyCompany: false,
      // 就餐类型
      diningTypes: [
        { id: "早餐", value: 1 },
        { id: "午餐", value: 2 },
        { id: "晚餐", value: 3 },
        { id: "接待餐", value: 4 },
        // { id: "其它", value: 5 },
      ],
      // 菜品类型
      foodTypes:"",

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      photo: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        price: undefined,
        password: undefined,
        type: undefined,
        photo: undefined,
      },
      // 表单参数
      form: {},
      MixinUploadAllApi:
        process.env.VUE_APP_BASE_API + "/file/upload/single",
      // 表单校验
      rules: {
        name: [
          { required: true, message: "菜品名称不能为空", trigger: "blur" },
          {
            required: false,
            pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/,
            message: "菜品名称不能为特殊字符",
            trigger: "blur",
          },
        ],
        price: [
          { required: true, message: "菜品单价不能为空", trigger: "blur" },
        ],
        // bornDate: [
        //   { required: true, message: "请选择菜品时段", trigger: "change" }
        // ],
        // diningType: [
        //   { required: true, message: "请选择就餐类型", trigger: "change" }
        // ],
        photo: [
          { required: true, message: "图片路径不能为空", trigger: "blur" },
        ],
        foodType: [
          { required: true, message: "请选择菜品类型", trigger: "change" },
        ],
        companyId: [
          { required: true, message: "请选择所属公司", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getCompanyList();
    this.listType();
  },
  methods: {
    listType() {
      listType().then(response => {
        this.foodTypes = response.data.list;
      });
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listFood(this.queryParams).then((response) => {
        this.foodList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        price: undefined,
        password: undefined,
        type: undefined,
        photo: undefined,
        createTime: undefined,
      };
      this.resetForm("form");
    },
    // 主体
    uploadSuccess(res) {
      //console.log(res)
      this.photoqiye = res.data;
      this.$set(this.form.photo, "photo", res.data);
      this.$refs["form.photo"].validateField("photo");
    },
    /** 图片上传之前的校验  */
    beforeImgUpload(file) {
      const isLt1M = file.size / 5120 / 5120 < 1;
      if (!isLt1M) {
        this.msgWarning("上传图片大小不能超过 5MB!");
      }
      var FileExt = file.name.replace(/.+\./, "");
      if (["jpg", "jpeg", "png"].indexOf(FileExt.toLowerCase()) === -1) {
        this.msgWarning("请上传后缀名为jpg/jpeg/png的图片附件！");
        return false;
      }
      return isLt1M;
    },

    beforeFileUpload(file) {
      console.log("file.type========:" + file.type);
      // const fileType = file.type === 'image/xls' || file.type === 'image/xlsx'
      const isLt10M = file.size / 1024 / 1024 < 10;
      // if (!fileType) {
      //   this.$message.error("上传文件只能是 xls和xlsx 格式!");
      //   return false;
      // }
      if (!isLt10M) {
        this.$message.error("上传文件大小不能超过 10M!");
        return false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.getDateList();
      this.reset();
      this.notModifyCompany = false;
      this.open = true;
      this.title = "添加菜品";
      this.fileListqiye = [];
      this.photo = "";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getFood(id).then((response) => {
        this.getDateList();
        this.form = response.data;
        this.photo = response.data.photo;
        this.form.photo = response.data.photo;
        this.photoqiye = response.data.photo;
        this.notModifyCompany = true;
        this.open = true;
        this.title = "修改菜品";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      // this.form.photo = this.photoqiye;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateFood(this.form).then((response) => {
              if (response.code == 0) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
                this.form.photo = undefined;
              }
            });
          } else {
            addFood(this.form).then((response) => {
              if (response.code == 0) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
                this.form.photo = undefined;
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除"' + row.name + '"的菜品?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delFood(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有菜品?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportFood(queryParams);
        })
        .then((response) => {
          // console.log(response)
          this.download(response.data);
        })
        .catch(function () {});
    },
    /** 获取时间信息 */
    getDateList() {
      getDate().then((response) => {
        this.dates = response.data;
      });
    },
    /** 获取公司信息 */
    getCompanyList() {
      getCompanys().then((response) => {
        this.companys = response.data;
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "菜品导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        this.download(response.data);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.message, "导入结果", {
        dangerouslyUseHTMLString: true,
      });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
<style>
.news-image {
  width: 50px;
  height: 50px;
}
.updateimg {
  width: 20%;
  max-width: 500px;
  min-width: 200px;
  float: left;
}
.updateimg img {
  max-width: 500px;
}
</style>
